package com.lego.servlet;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.lego.bean.User;
import com.lego.dao.UserDao;
import com.lego.dao.impl.UserDaoImpl;
import com.lego.service.UserService;
import com.lego.service.impl.UserServiceImpl;

@MultipartConfig
@WebServlet("/changeInfo.do")
public class ChangeInfoServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserService us = new UserServiceImpl();
		request.setCharacterEncoding("utf-8");
		String nickName = request.getParameter("nickName");//昵称
		String password = request.getParameter("password");//密码
		boolean isChangeName = false;//昵称是否发生改变
		boolean isChangePwd = false;//密码是否发生改变
		HttpSession session = request.getSession();
 	   	Object u = session.getAttribute("loginUser");//获取session登录对象
 	   	//获取登录的用户信息
 	   	User loginUser = null;
 	   	if (u != null) {
 	   		try {
 	            loginUser = (User) u;
 	        } catch (ClassCastException e) {
 	            // 处理类型转换失败的情况
 	            System.err.println("用户未登录");
 	        }
 	    }
 	   	//判断密码是否发生改变
		if(password!=null&&!password.equals("")&&!password.equals(loginUser.getPassword())) {
			isChangePwd = true;
		}
		//判断昵称是否发生改变
		if(nickName!=null&&!nickName.equals("")&&!nickName.equals(loginUser.getNickName())) {
			isChangeName = true;
		}
		//获取userId
		int userId = 0;
		if(loginUser!=null) {
			userId = loginUser.getUserId();
		}
		System.out.println("");
		System.out.println(isChangeName+"+"+isChangePwd);
		//昵称发生了改变，就改变昵称
		if(isChangeName) {
			int row = us.changeNickName(nickName,userId);
			if(row!=1) {
				System.out.println("昵称修改失败");
			}
		}
		if(isChangePwd) {
			int row = us.changePwd(password,userId);
			if(row!=1) {
				System.out.println("密码修改失败");
			}
		}
		//该变量记录 是否修改了封面
		boolean change = false;
		int result = 0;
		Part part = request.getPart("headImg");
		if(part != null && part.getSize() > 0){
			if(part.getContentType().contains("image")) {
				String fileName = UUID.randomUUID()+"_"+part.getSubmittedFileName();
				String savePath = "c:/legoImage/headImg/"+fileName;
				String visitPath = "/lego/headImg/"+fileName;
				part.write(savePath);
				//认为修改了封面
				change = true;
				result = us.changeHeadImg(visitPath,userId);
			}
		}
		//删除原来的图片
		if(result == 1 && change) {
			String oldCover = loginUser.getHeadImg();
			if(!"/demo/headImg/default.jpeg".equals(oldCover)) {
				String[] strs = oldCover.split("/");
				String fileName = strs[strs.length-1];
				File file = new File("c:/legoImage/headImg/"+fileName);
				if(file.exists()) {
					file.delete();
				}
			}
		}
		
		if(isChangePwd){
			//修改密码，清空session，跳转到login.jsp
			session.removeAttribute("loginUser");
			response.sendRedirect("login.jsp");
		}else if(change||isChangeName) {
			//清空session，重新设置session
			String userName = loginUser.getUserName();
			password = loginUser.getPassword();
			User user = us.loginUser(userName, password);
			session.removeAttribute("loginUser");
			System.out.println(user);
			session.setAttribute("loginUser", user);
			response.sendRedirect("personal.jsp");
		}
	}
}
